# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
uuid    = require 'uuid'
router = express.Router()
module.exports = router

router.all '/', (req, res, next) ->

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    where_clause = "(
        bin_num like $1 or card_name like $1 or
        issuer_code like $1 or issuer_name like $1
    )"

    # 查询记录总数
    await client.query \
        "select count(*) as count from p2_blacklist where #{ where_clause }",
        ['%' + res.locals.keyword + '%'], defer err, result
    if err then done(client); return next(err)
    res.locals.total = result.rows[0].count

    # 查询当前页面中显示的记录
    await client.query \
        "select * from p2_blacklist where #{ where_clause }
            order by serial offset $2::int limit $3::int", [
            '%' + res.locals.keyword + '%',
            res.locals.offset,
            res.locals.page_rows
        ], defer err, result
    if err then done(client); return next(err)
    done()

    res.render 'p2/blacklist', records: result.rows

router.get '/new', (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '新增卡bin黑名单'
    res.render 'p2/blacklist/new'

router.post '/new', (req, res, next) ->
    for k in ['bin_num', 'issuer_code', 'issuer_name',
        'card_name','debit_credit_flag', 'bin_len', 'card_no_len']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); next(err)

    await client.query \
        "insert into p2_blacklist(
            bin_num, issuer_code, issuer_name, card_name,
            debit_credit_flag, bin_len, card_no_len
        ) values ($1, $2, $3, $4, $5, $6, $7)", [
                req.body.bin_num,
                req.body.issuer_code,
                req.body.issuer_name,
                req.body.card_name,
                req.body.debit_credit_flag,
                req.body.bin_len,
                req.body.card_no_len
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.redirect '/p2/blacklist'

# 获取用户输入（卡 bin 号）的其他参数
router.post '/cardbin', (req, res, next) ->
    res.type('json')

    return next(new Error("请求缺少参数bin_num")) if not req.body.bin_num

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    # 查询卡bin信息
    await client.query \
        "select * from pay_cardbin where bin_num = #{req.body.bin_num}::text
         order by card_type limit 1",
         defer err, result
    if err then done(client); return next(err)
    done()
    cardbin = {}
    if result.rowCount > 0
       cardbin.issuer_code = if result.rows[0].issuer_code then result.rows[0].issuer_code else "--"
       cardbin.issuer_name = if result.rows[0].issuer_name then result.rows[0].issuer_name else "--"
       cardbin.card_name = if result.rows[0].card_name then result.rows[0].card_name else "--"
       cardbin.debit_credit_flag = if result.rows[0].debit_credit_flag then result.rows[0].debit_credit_flag else "--"
       cardbin.bin_len = if result.rows[0].bin_len then result.rows[0].bin_len else "--"
       cardbin.card_no_len = if result.rows[0].card_no_len then result.rows[0].card_no_len else "--"

    cardbin = JSON.stringify cardbin

    res.json succ: true, cardbin: cardbin

# 修改用户界面
router.get '/edit/:id', (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '修改卡bin信息'

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    # 查询信息填充表单字段
    await client.query \
        "select * from p2_blacklist
            where serial = $1::int", [
            parseInt(req.params.id) or 0,
        ], defer err, result
    if err then done(client); return next(err)
    done()
    if result.rows.length != 1
        return next(new Error("查无此卡bin黑名单记录[#{req.params.id}]"))

    record = result.rows[0]
    res.render 'p2/blacklist/edit', record: record


# 修改卡bin黑名单信息
router.post '/edit', (req, res, next) ->
    for k in ['serial','bin_num', 'issuer_code', 'issuer_name',
        'card_name', 'debit_credit_flag', 'bin_len', 'card_no_len']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update p2_blacklist set
            bin_num = $1, issuer_code = $2, issuer_name = $3,
            card_name = $4, debit_credit_flag = $5,
            bin_len = $6, card_no_len = $7
        where serial = $8", [
                req.body.bin_num,
                req.body.issuer_code,
                req.body.issuer_name,
                req.body.card_name,
                req.body.debit_credit_flag,
                req.body.bin_len,
                req.body.card_no_len,
                req.body.serial
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.redirect '/p2/blacklist'


# 禁用
router.post '/disable', (req, res, next) ->
    res.type('json')
    for k in ['serial','disabled']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update p2_blacklist set disabled = $1
            where serial = $2", [
            req.body.disabled,
            req.body.serial
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.json succ: true, redirect: '/p2/blacklist'


# 删除用户
router.post '/delete', (req, res, next) ->
    res.type('json')
    for k in ['serial']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "delete from p2_blacklist where serial = $1", [
            req.body.serial
        ], defer err, result

    done()
    return res.json succ: true, redirect: '/p2/blacklist'
